package bookmanagementsystem.gui;

import bookmanagementsystem.dao.AdminDAO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ModifyPasswordFrame extends JFrame {
    private JTextField oldPasswordField;
    private JTextField newPasswordField;
    private JButton confirmButton;
    private String currentAdminID;

    public ModifyPasswordFrame(String adminID) {
        this.currentAdminID = adminID;
        setTitle("修改管理员密码");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        initComponents();
        addComponentsToFrame();
        addActionListeners();
    }

    private void initComponents() {
        oldPasswordField = new JTextField(20);
        newPasswordField = new JTextField(20);
        confirmButton = new JButton("确认修改");
    }

    private void addComponentsToFrame() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.add(new JLabel("旧密码："));
        panel.add(oldPasswordField);
        panel.add(new JLabel("新密码："));
        panel.add(newPasswordField);
        panel.add(confirmButton);

        getContentPane().add(panel);
    }

    private void addActionListeners() {
        confirmButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String oldPassword = oldPasswordField.getText();
                String newPassword = newPasswordField.getText();


                AdminDAO adminDAO = new AdminDAO();
                if (adminDAO.loginAdmin(currentAdminID, oldPassword)) {
                    if (adminDAO.updateAdminPassword(currentAdminID, newPassword)) {
                        JOptionPane.showMessageDialog(ModifyPasswordFrame.this, "密码修改成功！");
                        dispose(); // 关闭当前修改密码界面
                    } else {
                        JOptionPane.showMessageDialog(ModifyPasswordFrame.this, "密码修改失败，请联系管理员。");
                    }
                } else {
                    JOptionPane.showMessageDialog(ModifyPasswordFrame.this, "旧密码输入错误，请重新输入。");
                }
            }
        });
    }
}